using System;
using System.Collections;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using Holoville.HOTween;
using Holoville.HOTween.Plugins;
using I2.Loc;
using Photon;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameController : Photon.MonoBehaviour
{
	public class PlayerInfo
	{
		public int id;

		public string name;

		public int points;

		public PunTeams.Team team;

		public string idPlayer;

		public PlayerInfo(int id, string name, int points, PunTeams.Team team, string idPlayer)
		{
			this.id = id;
			this.name = name;
			this.points = points;
			this.team = team;
			this.idPlayer = idPlayer;
		}

		public static int SortForTDM(PlayerInfo a, PlayerInfo b)
		{
			if (a.points != b.points)
			{
				return a.points.CompareTo(b.points) * -1;
			}
			if (PhotonNetwork.player.ID == a.id)
			{
				return -1;
			}
			if (PhotonNetwork.player.ID == b.id)
			{
				return 1;
			}
			return string.Compare(a.name, b.name);
		}

		public static int SortForFree(PlayerBehavior a, PlayerBehavior b)
		{
			if (a.points != b.points)
			{
				return a.points.CompareTo(b.points) * -1;
			}
			return 0;
		}
	}

	public static GameController instance;

	private IRoundBasedGameMode _currentGameMode;

	public mapType currentMapType;

	[HideInInspector]
	public EntityBehavior carScript;

	[HideInInspector]
	public Rigidbody curCarRigidBody;

	public Vector3 aimHit;

	public bool useLestncu;

	public GameObject myPlayer;

	public PlayerBehavior playerScript;

	[HideInInspector]
	public bool useZipLine;

	public GameObject starsRespawn;

	public GameObject spisokStars;

	public GameObject spisokCars;

	private MeshRenderer[] arrPointStar;

	private bool[] arrPointStarNoEmpty;

	public Transform gameUI;

	[HideInInspector]
	public WeaponManager weaponManagerScripts;

	public GameObject cameraGame;

	public TPSCamera tpsCamera;

	public GameObject blockPanel;

	public List<PlayerBehavior> listPlayers = new List<PlayerBehavior>();

	public Dictionary<int, PlayerBehavior> actualPlayers = new Dictionary<int, PlayerBehavior>();

	public Dictionary<int, PlayerBehavior> ignoredPlayers = new Dictionary<int, PlayerBehavior>();

	private List<PlayerBehavior> delPlayerFromList = new List<PlayerBehavior>();

	public List<EntityBehavior> arrAllCar = new List<EntityBehavior>();

	public Dictionary<int, EntityBehavior> viewIdToCar = new Dictionary<int, EntityBehavior>();

	public GameObject objAllSectors;

	public UIGrid gridScript;

	public AudioClip soundGameFon1;

	public AudioClip soundGameFon2;

	public AudioClip soundGameFon3;

	public AudioClip soundResaultStars;

	private clearMessage lbClaer1;

	private clearMessage lbClaer2;

	private clearMessage lbClaer3;

	public showResaultStars starsAnimScript;

	public int curKolStar;

	public int offlineKolKill;

	public int offlineKolDied;

	public int resaultKolStars;

	public float timeGame;

	public ControllsModifire curScriptLestnica;

	public List<MaterialPlayer> listMaterialPlayer = new List<MaterialPlayer>();

	public Shader defaultShaderForPlayer;

	[HideInInspector]
	public float dirRotateCar;

	[HideInInspector]
	public UICamera camNGUI;

	public TypeGame curTypeGame;

	[HideInInspector]
	public Color colorMyName = Color.blue;

	public LayerMask collisionGround;

	[HideInInspector]
	public long gameStartUnixTime;

	private IEnumerator _switchCam;

	private TankArrowsController _tankArrowsController;

	private int _startCups;

	private int _startLeagueIndex;

	public float RL_TimeScale = 1.4f;

	public Vector3 RL_Gravity;

	public int _startTimer;

	private int _timeLastClosingDevice;

	private int _timeForLeaveToLobby = 60;

	public List<TypeGame> typeGameWithFlag = new List<TypeGame>();

	public IRoundBasedGameMode CurrentGameMode
	{
		get
		{
			if (_currentGameMode == null)
			{
				throw new InvalidOperationException("Не существует IRoundBasedGameMode для текущего режима");
			}
			return _currentGameMode;
		}
		set
		{
			_currentGameMode = value;
		}
	}

	public TankArrowsController tankArrowsController
	{
		get
		{
			if (_tankArrowsController == null)
			{
				_tankArrowsController = UnityEngine.Object.Instantiate(Resources.Load<TankArrowsController>("Prefabs/TankArrowsController"));
				_tankArrowsController.gameObject.SetActive(false);
			}
			return _tankArrowsController;
		}
	}

	public int StartCups
	{
		get
		{
			return _startCups;
		}
	}

	public int StartLeagueIndex
	{
		get
		{
			return _startLeagueIndex;
		}
	}

	public static event Action changeLevel;

	private void Awake()
	{
		instance = this;
		if (instance.curTypeGame == TypeGame.normal)
		{
			_startCups = CupsManager.Cups;
			_startLeagueIndex = CupsManager.CurrentLeagueIndex;
		}
		colorMyName.r = 0.019f;
		colorMyName.g = 0.54f;
		colorMyName.b = 1f;
		tpsCamera = UnityEngine.Object.FindObjectOfType<TPSCamera>();
		if (defaultShaderForPlayer == null)
		{
			defaultShaderForPlayer = Shader.Find("Custom/DiffuseColor");
		}
		Time.maximumDeltaTime = 0.333f;
		if (ParametersLevel.instance != null)
		{
			currentMapType = ParametersLevel.instance.currentMapType;
		}
		if (spisokStars == null)
		{
			spisokStars = GameObject.FindGameObjectWithTag("Spisok_Stars");
		}
		if (starsRespawn == null)
		{
			starsRespawn = GameObject.FindGameObjectWithTag("Stars_Respawn");
		}
		if (spisokCars == null)
		{
			spisokCars = GameObject.FindGameObjectWithTag("Spisok_Cars");
		}
		HOTween.Init(false, false, false);
		if (cameraGame == null)
		{
			cameraGame = GameObject.FindGameObjectWithTag("MainCamera");
		}
		gameStartUnixTime = FlurryWrapper.CurrentUnixTime;
		SetGameMode();
		CupsManager.StartGame();
		if (curTypeGame == TypeGame.RocketLeague)
		{
			Time.timeScale = RL_TimeScale;
			Physics.gravity = RL_Gravity;
		}
		else
		{
			Time.timeScale = 1f;
			Physics.gravity = new Vector3(0f, -9.81f, 0f);
		}
	}

	public void SetGameMode()
	{
		if (settings.offlineMode)
		{
			if (settings.learningCompleted && starsRespawn != null)
			{
				arrPointStar = starsRespawn.GetComponentsInChildren<MeshRenderer>();
				arrPointStarNoEmpty = new bool[arrPointStar.Length];
			}
			if (IOSInternetConnection.isEnable)
			{
				curTypeGame = controllerLoadingGame.typeGame;
			}
			GameModeMetrix("Adventure");
			return;
		}
		curTypeGame = (TypeGame)(int)PhotonNetwork.room.customProperties[controllerConnectPhoton._typeGame];
		if (IOSInternetConnection.isEnable)
		{
			curTypeGame = controllerLoadingGame.typeGame;
		}
		switch (curTypeGame)
		{
		case TypeGame.normal:
			GameModeMetrix("PVP Sandbox");
			break;
		case TypeGame.race:
			GameModeMetrix("Race");
			break;
		case TypeGame.tanks:
			GameModeMetrix("Tanks");
			break;
		case TypeGame.TDM:
			GameModeMetrix("Team Deathmatch");
			break;
		case TypeGame.SkyBlock:
			GameModeMetrix("SkyBlock");
			break;
		case TypeGame.CopsAndRobbers:
			GameModeMetrix("Cops And Robbers");
			break;
		case TypeGame.RocketLeague:
			GameModeMetrix("Rocket League");
			break;
		case TypeGame.Pixelmon:
			GameModeMetrix("Pixelmon");
			break;
		case TypeGame.WalkingRobots:
			GameModeMetrix("Walking Robots");
			break;
		case TypeGame.TitanfallV2:
			GameModeMetrix("TitanfallV2");
			break;
		case TypeGame.deathmath:
		case TypeGame.Zombe:
		case TypeGame.Lobby:
		case TypeGame.OnlineSandbox:
		case TypeGame.Offline:
		case TypeGame.Unknown:
			break;
		}
	}

	public PhotonView GetPlayePhotonViewWithID(int id)
	{
		foreach (PlayerBehavior listPlayer in listPlayers)
		{
			if (listPlayer.photonView.viewID == id)
			{
				return listPlayer.photonView;
			}
		}
		BCWDebug.LogError("Can't find player photon view with ID: " + id);
		return null;
	}

	private void Start()
	{
		if (!settings.offlineMode && curTypeGame == TypeGame.normal && JSONManager.Instance.ServerTimeLoad())
		{
			_startTimer = JSONManager.Instance.GetServerTime();
		}
		if (IOSInternetConnection.isEnable)
		{
			controllerConnectGame.thisScript.instantiateNetworkObjects(controllerConnectPhoton.thisScript.chooseTypeGame);
		}
		else if (settings.offlineMode)
		{
			controllerConnectGame.thisScript.instantiateNetworkObjects();
		}
		if (!settings.learningCompleted)
		{
			ManagerPreloadingSectors.thisScript.proveritStatusLoading();
		}
		camNGUI = UnityEngine.Object.FindObjectOfType<UICamera>();
		WalkWindow.instance.HideTextureDamage();
		MapWindow.ResetBoundsMap();
		if (!settings.includePreloadingSectors)
		{
			showWindowGame();
		}
		TutorialDestroyer();
		StartCoroutine(ReportThatTimeHasPassed());
		settings.gameModeChange += ResetAllCar;
	}

	private IEnumerator ReportThatTimeHasPassed()
	{
		while (true)
		{
			yield return new WaitForSeconds(30f);
			TemporalProductManager.RefreshTime(30);
		}
	}

	private void TutorialDestroyer()
	{
		if (settings.learningCompleted)
		{
			TutorialButton[] componentsInChildren = WindowManager.instance.GetComponentsInChildren<TutorialButton>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				UnityEngine.Object.Destroy(componentsInChildren[i]);
			}
		}
	}

	private void OnApplicationPause(bool isPaused)
	{
		if (isPaused && !PanelEndGameRewardUI.isGiveReward)
		{
			SessionReputationManager.Instance.SaveRewardOnQuit();
		}
		TimeSpentInGameModeMetrix();
		if (settings.offlineMode)
		{
			return;
		}
		if (isPaused)
		{
			BCWDebug.LogError(BCWServer.GetLocalUnixTime().ToString());
			_timeLastClosingDevice = BCWServer.GetLocalUnixTime();
			return;
		}
		BCWDebug.LogError(BCWServer.GetLocalUnixTime().ToString());
		if (_timeLastClosingDevice + _timeForLeaveToLobby < BCWServer.GetLocalUnixTime())
		{
			exitToMenu();
			exitAfterDisconect();
		}
	}

	public void ChangeLevel()
	{
		if (GameController.changeLevel != null)
		{
			GameController.changeLevel();
		}
	}

	private void OnDestroy()
	{
		PhotonView.currentShakalIdForOffline = 10000;
		if (!PanelEndGameRewardUI.isGiveReward)
		{
			SessionReputationManager.Instance.SaveRewardOnQuit();
		}
		listPlayers.Clear();
		settings.gameModeChange -= ResetAllCar;
	}

	public void updateLbOfflineEndGame()
	{
	}

	private void GameModeMetrix(string gameModeName)
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		dictionary.Add("Enter in to the mode", gameModeName);
		FlurryWrapper.LogEvent(FlurryWrapper.EV_GAME_MODES, dictionary);
	}

	private void ReceivedRewardMetrix()
	{
		if (!(SessionReputationManager.Instance == null))
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			int receivedRewardCount = SessionReputationManager.Instance.ReceivedRewardCount;
			dictionary.Add((CupsManager.CurrentLeagueIndex + 1).ToString(), receivedRewardCount.ToString());
			if (settings.offlineMode)
			{
				FlurryWrapper.LogEvent(FlurryWrapper.EV_REPUTATION_RETURN_TO_LOBBY_STAGE_OFFLINE, dictionary);
			}
			else if (instance.curTypeGame == TypeGame.normal)
			{
				FlurryWrapper.LogEvent(FlurryWrapper.EV_REPUTATION_RETURN_TO_LOBBY_STAGE_ONLINE, dictionary);
			}
		}
	}

	private void CheckIfPlayerLeave()
	{
		bool flag = false;
		int getawayResult = 0;
		if (GameInfoWindow.instance.resultWindow != null)
		{
			flag = GameInfoWindow.instance.resultWindow.ReturnGetawayResult(ref getawayResult);
		}
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		switch (curTypeGame)
		{
		case TypeGame.TDM:
			dictionary.Add("Team_Deathmatch", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.tanks:
			dictionary.Add("Tanks", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.race:
			dictionary.Add("Racing", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.Zombe:
			dictionary.Add("Zombie", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.SkyBlock:
			dictionary.Add("SkyBlock", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.RocketLeague:
			dictionary.Add("Rocket League", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.CopsAndRobbers:
			dictionary.Add("Cops And Robbers", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.Pixelmon:
			dictionary.Add("Pixelmon", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.WalkingRobots:
			dictionary.Add("Titanfall", (!flag) ? "complete" : "left");
			dictionary.Add("Penalty", (!flag) ? "without penalty" : "with penalty");
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MODES_LEAVES_RATING, dictionary);
			break;
		case TypeGame.Lobby:
		case TypeGame.OnlineSandbox:
		case TypeGame.Offline:
		case TypeGame.Unknown:
			break;
		}
	}

	public void TimeSpentInGameModeMetrix()
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		string empty = string.Empty;
		if (settings.offlineMode)
		{
			empty = "Adventure";
		}
		else
		{
			switch (curTypeGame)
			{
			case TypeGame.normal:
				empty = "PVP Sandbox";
				break;
			case TypeGame.race:
				empty = "Race";
				break;
			case TypeGame.tanks:
				empty = "Tanks";
				break;
			case TypeGame.TDM:
				empty = "Team Deathmatch";
				break;
			case TypeGame.Zombe:
				empty = "Zombie";
				break;
			case TypeGame.SkyBlock:
				empty = "SkyBlock";
				break;
			case TypeGame.CopsAndRobbers:
				empty = "Cops And Robbers";
				break;
			case TypeGame.RocketLeague:
				empty = "Rocket League";
				break;
			case TypeGame.Pixelmon:
				empty = "Pixelmon";
				break;
			case TypeGame.WalkingRobots:
				empty = "Walking Robots";
				break;
			case TypeGame.TitanfallV2:
				empty = "TitanfallV2";
				break;
			default:
				empty = "Other";
				break;
			}
		}
		dictionary.Add(empty + " Time Spent", FlurryWrapper.TimeSpend(FlurryWrapper.CurrentUnixTime - gameStartUnixTime));
		FlurryWrapper.LogEvent(FlurryWrapper.EV_GAME_MODES, dictionary);
	}

	public void animResultStars()
	{
		if (resaultKolStars > 0)
		{
			resaultKolStars--;
			starsAnimScript.updateShowKolStars(starsAnimScript.showKolStars + 1);
			if (VolumeController.IsSoundEnable)
			{
				NGUITools.PlaySound(soundResaultStars);
			}
			HOTween.To(this, 0.5f, new TweenParms().Prop("resaultKolStars", resaultKolStars).UpdateType(UpdateType.TimeScaleIndependentUpdate).OnComplete(animResultStars));
		}
	}

	private void createStarsToPointsRespawn()
	{
		UnityEngine.Object original = Resources.Load("Bonuse/Star");
		for (int i = 0; i < arrPointStarNoEmpty.Length; i++)
		{
			arrPointStarNoEmpty[i] = false;
		}
		curKolStar = 0;
		int num = Mathf.Min(settings.kolStarOnLevel, arrPointStar.Length);
		for (int j = 0; j < num; j++)
		{
			int num2 = UnityEngine.Random.Range(0, arrPointStar.Length);
			if (!arrPointStarNoEmpty[num2])
			{
				arrPointStarNoEmpty[num2] = true;
				Vector3 position = arrPointStar[num2].transform.position;
				GameObject gameObject = (GameObject)UnityEngine.Object.Instantiate(original, position, Quaternion.identity);
				gameObject.transform.parent = spisokStars.transform;
			}
			else
			{
				j--;
			}
		}
	}

	public void switchInterface(bool car)
	{
		if (MapWindow.instance != null && MapWindow.instance.worldMapShow)
		{
			return;
		}
		HitMarks.instance.gameObject.SetActive(true);
		rednessScreen.inst.gameObject.SetActive(true);
		if (car)
		{
			WindowManager.instance.HideWindow(typeof(WalkWindow));
			WalkWindow.instance.panelJoystick.gameObject.SetActive(false);
			WindowManager.instance.ShowWindow(typeof(CarWindow), false);
			WindowManager.instance.HideWindow(typeof(BoadWindow));
			BoadWindow.instance.interfaceForBoatWithWeapon.SetActive(false);
			if (!(carScript != null))
			{
				return;
			}
			CarWindow.instance.SetWeaponVisible(carScript.carWithWeapon);
			if (carScript.carWithWeapon)
			{
				if (CarWindow.instance.iconCarWeapon.mainTexture != null)
				{
					Resources.UnloadAsset(CarWindow.instance.iconCarWeapon.mainTexture);
				}
				Texture texture = Resources.Load<Texture>("AtlasGame/AG_" + carScript.GetCurrentSkin().name);
				if (texture == null)
				{
					texture = Resources.Load<Texture>("AtlasGame/" + carScript.nameSpritePreview);
				}
				CarWindow.instance.iconCarWeapon.mainTexture = texture;
			}
			CarWindow.instance.vehicle = carScript;
		}
		else
		{
			WalkWindow.instance.panelJoystick.gameObject.SetActive(true);
			WindowManager.instance.HideWindow(typeof(CarWindow));
			CarWindow.instance.SetWeaponVisible(false);
			WindowManager.instance.HideWindow(typeof(BoadWindow));
			BoadWindow.instance.interfaceForBoatWithWeapon.SetActive(false);
			CarWindow.instance.vehicle = null;
			WindowManager.instance.ShowWindow(typeof(WalkWindow));
		}
	}

	public void SwitchCam()
	{
		if (_switchCam == null)
		{
			_switchCam = SwitchCamCoroutine();
			StartCoroutine(_switchCam);
		}
	}

	private IEnumerator SwitchCamCoroutine()
	{
		while (playerScript == null || playerScript.inCar || playerScript.inHelic)
		{
			yield return new WaitForEndOfFrame();
		}
		_switchCam = null;
	}

	public void switchInterfaceBoad(bool inBoad)
	{
		if (MapWindow.instance.worldMapShow)
		{
			return;
		}
		if (inBoad)
		{
			WindowManager.instance.HideWindow(typeof(WalkWindow));
			WalkWindow.instance.panelJoystick.gameObject.SetActive(false);
			WindowManager.instance.HideWindow(typeof(CarWindow));
			CarWindow.instance.SetWeaponVisible(false);
			WindowManager.instance.ShowWindow(typeof(BoadWindow), false);
			if (carScript != null)
			{
				BoadWindow.instance.interfaceForBoatWithWeapon.SetActive(carScript.carWithWeapon);
			}
		}
		else
		{
			WindowManager.instance.ShowWindow(typeof(WalkWindow), false);
			WalkWindow.instance.panelJoystick.gameObject.SetActive(true);
			WindowManager.instance.HideWindow(typeof(BoadWindow));
			BoadWindow.instance.interfaceForBoatWithWeapon.SetActive(false);
			WindowManager.instance.HideWindow(typeof(CarWindow));
			CarWindow.instance.SetWeaponVisible(false);
		}
	}

	public void CheckInterfaceHelicopter(bool inHelic)
	{
		if (inHelic)
		{
			WindowManager.instance.ShowWindow(typeof(FlyWindow), false);
			WindowManager.instance.HideWindow(typeof(WalkWindow));
			FlyWindow.instance.vehicle = instance.playerScript.currentCar;
		}
		else
		{
			WindowManager.instance.HideWindow(typeof(FlyWindow));
			WindowManager.instance.ShowWindow(typeof(WalkWindow), false);
			FlyWindow.instance.vehicle = null;
		}
	}

	public void hideAllPanels()
	{
		WindowManager.instance.HideAllWindow();
		HitMarks.instance.gameObject.SetActive(false);
		rednessScreen.inst.gameObject.SetActive(false);
		if (settings.offlineMode)
		{
			IndicatorMissions.SetVisible(false);
		}
		MapWindow.HideWorldMap();
		if (WalkWindow.instance.panelJoystick != null)
		{
			WalkWindow.instance.panelJoystick.gameObject.SetActive(false);
		}
	}

	public void showWindowPause()
	{
		WindowManager.instance.ShowWindow(typeof(PauseWindow), true);
	}

	public void showWindowGame()
	{
		WindowManager.instance.ShowWindow(typeof(GameTopWindow), true);
	}

	public void showLoadingMenu()
	{
		WindowManager.instance.HideAllWindow();
		MessageWindow.instance.SetVisiblePanelLoading(true, string.Empty);
	}

	public void pause()
	{
		showWindowPause();
		if (settings.offlineMode)
		{
			Time.timeScale = 0f;
		}
	}

	public void resume()
	{
		showWindowGame();
		if (settings.offlineMode)
		{
			Time.timeScale = 1f;
		}
	}

	public void replay()
	{
		Time.timeScale = 1f;
		settings.SaveCathedExeptionsToStorager();
		SceneManager.LoadScene("LoadingGame");
	}

	public void exitToMenu()
	{
		if ((bool)GameInfoWindow.instance)
		{
			GameInfoWindow.instance.resultWindow.GetawayResult();
		}
		if (playerScript != null)
		{
			playerScript.HandleInvisibleAchivment();
		}
		TimeSpentInGameModeMetrix();
		ReceivedRewardMetrix();
		CheckIfPlayerLeave();
		MessageWindow.instance.SetVisiblePanelLoading(true, "exit");
		MessageWindow.instance.panelLoading.GetComponent<SceneLoadBar>().tutorialSnowZone.SetActive(false);
		Time.timeScale = 1f;
		if (settings.offlineMode)
		{
			Invoke("loadSceneLoading", 0.5f);
			return;
		}
		PhotonNetwork.LeaveRoom();
		PhotonNetwork.Disconnect();
		controllerConnectGame.thisScript.stopRecconect();
	}

	public void exitAfterDisconect()
	{
		showLoadingMenu();
		loadSceneLoading();
	}

	private void loadSceneLoading()
	{
		BCWStorage.SaveAll();
		Input.ResetInputAxes();
		settings.SaveCathedExeptionsToStorager();
		SceneManager.LoadScene("LoadingMenu");
	}

	public void removeAllPlayersFromListBezObj()
	{
		foreach (PlayerBehavior listPlayer in listPlayers)
		{
			if (listPlayer == null)
			{
				delPlayerFromList.Add(listPlayer);
			}
		}
		foreach (PlayerBehavior delPlayerFrom in delPlayerFromList)
		{
			listPlayers.Remove(delPlayerFrom);
		}
		delPlayerFromList.Clear();
	}

	public void addPlayerToList(PlayerBehavior newPlayer, string nickName)
	{
		foreach (PlayerBehavior listPlayer in listPlayers)
		{
			if (newPlayer.Equals(listPlayer))
			{
				if ((bool)PvPLeaderbord.instance)
				{
					PvPLeaderbord.instance.Refrash();
				}
				return;
			}
		}
		listPlayers.Add(newPlayer);
		if ((bool)PvPLeaderbord.instance)
		{
			PvPLeaderbord.instance.Refrash();
		}
		if (GameInfoWindow.instance != null && !PVPManager.instance.endOfRound)
		{
			GameInfoWindow.instance.UpdateScrollForCurrentGameMode();
		}
	}

	public void removePlayerFromList(PlayerBehavior pb)
	{
		listPlayers.Remove(pb);
		if ((bool)PvPLeaderbord.instance)
		{
			PvPLeaderbord.instance.Refrash();
		}
		if (!PVPManager.instance.endOfRound)
		{
			GameInfoWindow.instance.UpdateScrollForCurrentGameMode();
		}
	}

	public int sortListPlayers()
	{
		listPlayers.Sort((PlayerBehavior a, PlayerBehavior b) => b.sessionCupsCount.CompareTo(a.sessionCupsCount));
		for (int i = 0; i < listPlayers.Count; i++)
		{
			if (listPlayers[i] == playerScript)
			{
				return i + 1;
			}
		}
		return -1;
	}

	public void stopRecconect()
	{
		controllerConnectGame.thisScript.stopRecconect();
		exitAfterDisconect();
	}

	public void addMessageToListOnline(string msg, int chatIndex = 0, PunTeams.Team team = PunTeams.Team.none, ChatWindow.IdChatType idChat = ChatWindow.IdChatType.general)
	{
		if (!settings.offlineMode)
		{
			base.photonView.RPC("addMessageToList", PhotonTargets.Others, FilterBadWorld.FilterString(msg), chatIndex, team, idChat);
		}
	}

	[PunRPC]
	public void addMessageToList(string msg, int chatIndex = 0, PunTeams.Team team = PunTeams.Team.none, ChatWindow.IdChatType idChat = ChatWindow.IdChatType.general)
	{
		if (TDMController.isTeamGameType && TDMController.myTeam == PunTeams.Team.none)
		{
			return;
		}
		ChatInGameMessageFilterInterface checker = ChatInGameMessageFilterFactory.getChecker(idChat);
		if (checker == null || checker.check(team, TDMController.myTeam))
		{
			if (chatIndex == 0 && (bool)ChatWindow.instance && !msg.Contains("[e56717]") && !msg.Contains("[417c64]"))
			{
				ChatWindow.instance.chatRoom.AddMessageToScroll(msg, false, team, idChat);
			}
			GameTopWindow.instance.AddAndShowNextMessage(msg, chatIndex);
		}
	}

	public void addMessageWinnerOnline(string _winnerName)
	{
		if (!settings.offlineMode)
		{
			base.photonView.RPC("addMessageWinner", PhotonTargets.All, _winnerName);
		}
	}

	[PunRPC]
	public void addMessageWinner(string _winnerName)
	{
		string msg = string.Format(ScriptLocalization.Get("Game_PVP_msg/src_PlayerWinner"), _winnerName);
		GameTopWindow.instance.AddAndShowNextMessage(msg);
	}

	public void removePlayerWithID(int idPlayer)
	{
		if (listPlayers.RemoveAll((PlayerBehavior x) => x == null) > 0)
		{
			PvPLeaderbord.instance.Refrash();
		}
		foreach (PlayerBehavior listPlayer in listPlayers)
		{
			if (listPlayer.photonView.ownerId == idPlayer)
			{
				removePlayerFromList(listPlayer);
				UnityEngine.Object.Destroy(listPlayer.gameObject);
				return;
			}
		}
		if (instance.curTypeGame == TypeGame.race)
		{
			GameInfoWindow.instance.UpdateRaceScroll();
		}
	}

	public void CarTurnLeft()
	{
		InvokeRepeating("CarTurnLeftInvok", 0.02f, 0.02f);
	}

	public void CarTurnLeftInvok()
	{
		if (dirRotateCar > -0.75f)
		{
			dirRotateCar -= 0.05f;
		}
		else
		{
			CancelInvoke("CarTurnLeftInvok");
		}
	}

	public void CarTurnRight()
	{
		InvokeRepeating("CarTurnRightInvok", 0.02f, 0.02f);
	}

	public void CarTurnRightInvok()
	{
		if (dirRotateCar < 0.75f)
		{
			dirRotateCar += 0.05f;
		}
		else
		{
			CancelInvoke("CarTurnRightInvok");
		}
	}

	public void CarTurnForward()
	{
		dirRotateCar = 0f;
		CancelInvoke("CarTurnLeftInvok");
		CancelInvoke("CarTurnRightInvok");
	}

	private Material getMaterialForTexture(Texture oldTexture, Texture newText)
	{
		List<MaterialPlayer> list = new List<MaterialPlayer>();
		Material material = null;
		if (material == null)
		{
			MaterialPlayer materialPlayer = new MaterialPlayer();
			materialPlayer.curMaterial = new Material(defaultShaderForPlayer);
			materialPlayer.kolObjWithCurMaterial = 1;
			materialPlayer.curTexture = newText;
			materialPlayer.curMaterial.mainTexture = newText;
			listMaterialPlayer.Add(materialPlayer);
			return materialPlayer.curMaterial;
		}
		return material;
	}

	public void setMaterialForRenderer(Renderer curRend, Texture curText)
	{
		curRend.material = getMaterialForTexture(curRend.material.mainTexture, curText);
	}

	public void SetMaterialAndTextureForPlayer(Humanoid player, Texture texture)
	{
		if (player.mainMaterial != null)
		{
			player.mainMaterial.mainTexture = texture;
		}
		else if (player != null)
		{
			player.Invisible(player.IsInvisible);
		}
	}

	public static void SetMaterialAndTextureForEnemy(GameObject enemyObj, Texture texture, EnemyBehavior enemy)
	{
		Renderer[] componentsInChildren = enemyObj.GetComponentsInChildren<Renderer>(true);
		Material material = new Material(instance.defaultShaderForPlayer);
		material.mainTexture = texture;
		material.SetColor("_Color", Color.red);
		material.SetFloat("_Alpha", 1f);
		Renderer[] array = componentsInChildren;
		foreach (Renderer renderer in array)
		{
			if (renderer.gameObject.tag != "Weapon")
			{
				renderer.material = material;
			}
		}
		if (enemy != null)
		{
			enemy.mainMaterial = material;
		}
	}

	public void StartTimerDeadPlayerInTrasnport(float iTimeToDead)
	{
		if (carScript != null)
		{
			carScript.isAcitveContol = false;
		}
		Invoke("DeadPlayerInTrasnport", iTimeToDead);
	}

	public void StopTimerDeadPlayerInTrasnport()
	{
		if (myPlayer.transform.position.y < -1.5f)
		{
			base.gameObject.transform.rotation = Quaternion.identity;
			HOTween.To(myPlayer.transform, 1f, new TweenParms().Prop("position", new PlugVector3Y(-1.5f)).Ease(EaseType.Linear));
		}
		CancelInvoke("DeadPlayerInTrasnport");
	}

	public void StopTimerWhenOutOfTheWater()
	{
		CancelInvoke("DeadPlayerInTrasnport");
	}

	public void DeadPlayerInTrasnport()
	{
		playerScript.Kill(playerScript.viewId);
	}

	public void OnPhotonPlayerDisconnected(PhotonPlayer player)
	{
		if ((bool)GameInfoWindow.instance && GameInfoWindow.instance.gameObject.activeSelf && curTypeGame != TypeGame.TDM && curTypeGame != TypeGame.tanks && curTypeGame == TypeGame.race)
		{
			GameInfoWindow.instance.UpdateRaceScroll();
		}
	}

	public void OnPhotonPlayerConnected(PhotonPlayer player)
	{
		if ((bool)GameInfoWindow.instance && GameInfoWindow.instance.gameObject.activeSelf && curTypeGame != TypeGame.TDM && curTypeGame != TypeGame.tanks)
		{
		}
	}

	public void RestartLevel()
	{
		if (instance.playerScript != null)
		{
			instance.playerScript.Points = 0;
			instance.playerScript.reset(true);
			WindowManager.instance.ShowWindow(typeof(GameTopWindow), true);
		}
	}

	public void RestartLevel(SpawnPointChief.SpawnPoint spawnPoint)
	{
		if (instance.playerScript != null)
		{
			instance.playerScript.Points = 0;
			WindowManager.instance.ShowWindow(typeof(GameTopWindow), true);
		}
	}

	public void ResetAllCar()
	{
		if (settings.offlineMode)
		{
			return;
		}
		foreach (EntityBehavior item in arrAllCar)
		{
			item.reset();
			if (item is TitanBehavior)
			{
				(item as TitanBehavior).PropperlyHideTitan(0.1f);
			}
		}
	}

	public void ResetSettingsLevel()
	{
		if (settings.offlineMode)
		{
			return;
		}
		foreach (EntityBehavior item in arrAllCar)
		{
			if (item.isMine)
			{
				item.ResetCarWithDelay(0f);
			}
		}
		if (PrivateCarManager.instance != null && PrivateCarManager.instance.currentCar != null && typeof(CarBehavior) == PrivateCarManager.instance.currentCar.GetType())
		{
			((CarBehavior)PrivateCarManager.instance.currentCar).HideCar();
		}
	}

	public void OnMasterClientSwitched(PhotonPlayer newMasterClient)
	{
		if (PhotonNetwork.isMasterClient)
		{
			StartCoroutine(RestartCarAfterDelay());
			if (PixelmonController.instance != null)
			{
				PixelmonController.instance.SwitchMaster();
			}
			if (PVPManager.instance.needToChangeRoundIndex)
			{
				PVPManager.instance.roundIndex++;
				PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
				{
					controllerConnectPhoton._indexRound,
					PVPManager.instance.roundIndex
				} });
				PVPManager.instance.needToChangeRoundIndex = false;
			}
		}
	}

	private IEnumerator RestartCarAfterDelay()
	{
		yield return new WaitForSeconds(0.5f);
		foreach (EntityBehavior car in instance.arrAllCar)
		{
			if (car.health <= 0 && (car.isDead || car.initialPosition != car.transform.position) && !car.privateCar)
			{
				car.Disable();
			}
		}
	}

	public bool CanDeadInGame()
	{
		return settings.offlineMode || TDMController.instance == null || TDMController.instance.pvpStarted || instance.curTypeGame == TypeGame.normal;
	}

	public bool IsFlagGameType()
	{
		return typeGameWithFlag.Contains(instance.curTypeGame);
	}

	public PlayerBehavior FindPlayer(int ownerId)
	{
		foreach (PlayerBehavior listPlayer in listPlayers)
		{
			if (listPlayer.ownerId == ownerId)
			{
				return listPlayer;
			}
		}
		return null;
	}
}
